const express = require('express')
const router = express.Router()
const db = require('../mysql/index')
// 数据加密
const bcrypt = require('bcryptjs')
// 生成jwt
const jwt = require('jsonwebtoken')
// token配置文件
const tokenConfig = require('../tokenConfig')

// 登录接口
router.post('/login', (req, res) => {
    const userInfo = req.body
    const sql = 'select * from user where username=?'
    db.query(sql, userInfo.username, (err, results) => {
        if (err) {
            return res.send({ status: 1, msg: err.message })
        }
        if (results.length != 1) {
            return res.send({ status: 1, msg: '用户不存在，登录失败' })
        }
        // 验证密码是否正确
        const comparePassword = bcrypt.compareSync(userInfo.password, results[0].password)
        if (!comparePassword) {
            return res.send({ status: 1, msg: '密码错误，登录失败' })
        }
        // 生成token
        const token = jwt.sign({id:results[0].id, admin:results[0].admin, username: userInfo.username }, tokenConfig.secretKey, { expiresIn: tokenConfig.expiresIn })
        res.send({ status: 0, msg: '登录成功', admin: results[0].admin, token: `Bearer ${token}` })
    })

})

// 注册接口
router.post('/register', (req, res) => {
    const userInfo = req.body
    const sql = 'select * from user where username=?'
    // 查询是否存在该用户
    db.query(sql, userInfo.username, (err, results) => {
        if (err) {
            return res.send({ status: 1, msg: err.message })
        }
        // 用户已存在
        if (results.length == 1) {
            return res.send({ status: 1, msg: '该用户已存在' })
        }
        // 插入用户信息
        const sql = 'insert into user set ? '
        // 密码加密
        const password = bcrypt.hashSync(userInfo.password, 10)
        db.query(sql, { nickname: userInfo.nickname, username: userInfo.username, password, phone: userInfo.phone }, (err, results) => {
            // 执行sql失败
            if (err) {
                return res.send({ status: 1, msg: err.message })
            }
            // 插入数据失败
            if (results.affectedRows != 1) {
                return res.send({ status: 1, msg: '注册用户信息失败' })
            }
            res.send({ status: 0, msg: '用户注册成功' })
        })
    })
})

module.exports = router